package com.bruce.practice.dingding;
import cn.hutool.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import org.apache.commons.codec.binary.Base64;

/**
 * @author luotuan
 * @Description
 * @create 2020-08-03 21:04
 **/
public class DingDingMsgSendUtils {
    private static final Logger log = LoggerFactory.getLogger(DingDingMsgSendUtils.class);
    private String Webhook = "https://oapi.dingtalk.com/robot/send?access_token=ec54f903f74d35a0935a5397c65e3af68ec8933c6dc4fca04c847d7ffeef522e";
    /**
     * 调用钉钉官方接口发送钉钉消息（新版本，需要配置安全设置）
     * @param accessToken
     * @param secret
     * @param textMsg
     */
    private static void dealDingDingMsgSendNew(String accessToken, String secret, String textMsg) {
        Long timestamp = System.currentTimeMillis();
        String sign = getSign(secret,timestamp);
        String url = "https://oapi.dingtalk.com/robot/send?access_token=" + accessToken + "&timestamp=" + timestamp + "&sign=" + sign;
        System.out.println("url:"+url);
        try {
            log.info("【发送钉钉群消息】请求参数：url = {}, textMsg = {}", url, textMsg);
            String res = HttpUtil.post(url, textMsg);
            log.info("【发送钉钉群消息】消息响应结果：" + res);
        } catch (Exception e) {
            log.warn("【发送钉钉群消息】请求钉钉接口异常，errMsg = {}", e);
        }
    }

    /**
     * 计算签名
     * @param secret 密钥，机器人安全设置页面，加签一栏下面显示的SEC开头的字符
     * @return
     */
    private static String getSign(String secret,Long timestamp){
        String sign = null;
        try {
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)),"UTF-8");
            System.out.println(sign);
        }catch (Exception e){
            e.printStackTrace();
        }
        return sign;
    }
    /**
     * 发送钉钉群消息
     * @param accessToken
     * @param content
     */
    public static void sendDingDingMsg(String accessToken, String secret,String content) {
        String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + content + "\"}}";
        dealDingDingMsgSendNew(accessToken,secret,textMsg);
    }

    public static void main(String[] args) {
        String secret = "SECc8daa2b4f1ceb8b00297c635af70";
        String accessToken = "ec54f903f74d35a0935a5397c65e3af68ec8933c6dc4fca04c847d7ffeef522e";
        String context = "测试";
        sendDingDingMsg(accessToken,secret,context);
    }
}
